package hot;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author way
 * @create 2025-03-02 18:59
 */
public class _3_lengthOfLongestSubstring {
    public int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        int ans = 0;
        int left = 0;
        int[] cnt = new int[128];
        for (int right = 0; right < s.length(); right++) {
            char c = chars[right];
            cnt[c]++;
            while (cnt[c] > 1) {
                cnt[chars[left]]--;
                left++;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

    public int lengthOfLongestSubstring1(String s) {
        char[] chars = s.toCharArray();
        int ans = 0;
        int left = 0;
        int right = 0;
        HashSet<Character> set = new HashSet<>();

        while (right < s.length()) {
            char c = chars[right];
            while (set.contains(c)) {
                // 如果发现重复字符，移动 left 指针，直到移除重复字符
                set.remove(chars[left]);
                left++;
            }
            // 如果没有重复字符，扩展窗口
            set.add(c);
            ans = Math.max(ans, right - left + 1); // 更新最大长度
            right++;
        }
        return ans;
    }
}
